package com.i2silly.wxbot.thread;

import com.alibaba.fastjson.JSON;
import com.i2silly.wxbot.config.RobotConfiguration;
import com.i2silly.wxbot.config.TempCache;
import com.i2silly.wxbot.constant.WxRobotConstant;
import com.i2silly.wxbot.entity.BotChatroom;
import com.i2silly.wxbot.entity.BotContact;
import com.i2silly.wxbot.entity.BotRobot;
import com.i2silly.wxbot.pojo.ChatroomMember;
import com.i2silly.wxbot.pojo.WsReceive;
import com.i2silly.wxbot.service.IBotChatroomService;
import com.i2silly.wxbot.service.IBotContactService;
import com.i2silly.wxbot.service.IBotRobotService;
import com.i2silly.wxbot.utils.PubUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.Future;

/**
 * @program: wx-bot
 * @description：
 * @author: pzhongqiang@linewell.com
 * @date: 2020年11月28日 00:44:04
 */
@Component
public class HandleMessageTask {

    Logger logger = LoggerFactory.getLogger(HandleMessageTask.class);

    @Autowired
    private IBotRobotService robotService;

    @Autowired
    private RobotConfiguration robotConfig;

    @Autowired
    private IBotContactService contactService;

    @Autowired
    private IBotChatroomService chatroomService;

    @Autowired
    private TempCache cache;

    @Async("handleMessage")
    public AsyncResult<Boolean>  exec(WsReceive receive) {
        AsyncResult<Boolean> result = new AsyncResult<>(false);
        return result;
    }

    /**
     * 保存机器人
     *
     * @param s json数据
     * @return
     */
    @Async("saveRobot")
    public Future<BotRobot> saveRobot(String s) {
        boolean b;
        AsyncResult<BotRobot> result = null;
        // 保存机器人
        if (PubUtils.isNotEmpty(s)) {
            BotRobot bot = JSON.parseObject(s, BotRobot.class);
            BotRobot robot = robotService.getByWxid(bot.getWxid());
            if (robot != null) {
                bot.setId(robot.getId());
                b = robotService.updateById(bot);
            } else {
                bot.setId(PubUtils.getUUID());
                b = robotService.save(bot);
            }
           if (b) {
               result = new AsyncResult<>(bot);
           }
        }
        return  result;
    }

    /**
     * 保存所有联系人及群
     *
     * @param s 联系人数据
     * @return
     */
    @Async("saveContact")
    public Future<Boolean> saveContactList(String s) {
        AsyncResult<Boolean> result = new AsyncResult<>(false);
        if (PubUtils.isNotEmpty(s)) {
            Map<String, BotContact> contactMap = cache.getContacts();
            List<BotContact> robots = JSON.parseArray(s, BotContact.class);
            String botWechatId = robotConfig.getBotWechatId();
            // 获取数据库是否存在联系人
            List<BotContact> contacts = contactService.listByPid(botWechatId);
            List<BotContact> insertList = new ArrayList<>();
            List<String> delList = null;
            // 需过滤微信id
            String[] filterWxId = robotConfig.getFilter().split(",");
            List<String> wxids = new ArrayList<>();
            if (PubUtils.isEmpty(contacts)) {
                for (BotContact robot : robots) {
                    BotContact contact = checkContact(robot, filterWxId);
                    // 去重
                    if (null == contact || wxids.contains(contact.getWxid())) {
                        continue;
                    } else {
                        wxids.add(contact.getWxid());
                    }
                    // 放置预置缓存
                    contactMap.put(contact.getWxid(), contact);
                    insertList.add(contact);
                }
            } else {
                delList = new ArrayList<>();
                for (BotContact robot : robots) {
                    BotContact contact = checkContact(robot, filterWxId);
                    // 去重
                    if (null == contact || wxids.contains(contact.getWxid())) {
                        continue;
                    } else {
                        wxids.add(contact.getWxid());
                    }
                    contactMap.put(robot.getWxid(), contact);
                }
                // 获取联系人所有key即wxid
                List<String> set = new ArrayList<>(contactMap.keySet());
                for (BotContact contact : contacts) {
                    if (set.contains(contact.getWxid())) {
                        set.remove(contact.getWxid());
                    } else {
                        delList.add(contact.getId());
                    }
                }
                for (String key : set) {
                    insertList.add(contactMap.get(key));
                }
            }
            if (PubUtils.isNotEmpty(delList)) {
                contactService.removeByIds(delList);
            }
            if (PubUtils.isNotEmpty(insertList)) {
                contactService.saveBatch(insertList);
            }
            // 添加至缓存
            cache.addCache(WxRobotConstant.CONTACT_CACHE, contactMap);
            result = new AsyncResult<>(true);
        }
        return result;
    }

    /**
     * 弃用
     * 保存群信息
     * @param member 群及群成员
     * @return
     */
    @Async("saveChatroom")
    @Deprecated
    public Future<Boolean> saveChatroom(ChatroomMember member) {
        AsyncResult<Boolean> result = new AsyncResult<>(false);
        try {
            if (null != member) {
                Map<String, List<BotChatroom>> cacheChatrooms = cache.getChatrooms();
                String roomId = member.getRoomid();
                List<BotChatroom> chatrooms = chatroomService.listByChatroomIdAndPid(roomId, robotConfig.getBotWechatId());
                List<BotChatroom> insertList = new ArrayList<>();
                List<String> delList = null;
                BotChatroom botChatroom;
                List<String> list = member.getMember();
                List<BotChatroom> chatroomCache = new ArrayList<>();
                if (PubUtils.isNotEmpty(chatrooms)){
                    delList = new ArrayList<>();
                    for (BotChatroom chatroom : chatrooms) {
                        if (list.contains(chatroom.getMemberWxid())){
                            chatroomCache.add(chatroom);
                            list.remove(chatroom.getMemberWxid());
                        } else {
                            delList.add(chatroom.getId());
                        }
                    }
                }
                if (PubUtils.isNotEmpty(list)){
                    for (String s : list) {
                        botChatroom = new BotChatroom();
                        botChatroom.setId(PubUtils.getUUID());
                        botChatroom.setPid(robotConfig.getBotWechatId());
                        botChatroom.setChatroomWxid(roomId);
                        botChatroom.setMemberWxid(s);
                        chatroomCache.add(botChatroom);
                        insertList.add(botChatroom);
                    }
                }
                if (PubUtils.isNotEmpty(delList)) {
                    chatroomService.removeByIds(delList);
                }
                if (PubUtils.isNotEmpty(insertList)) {
                    chatroomService.saveBatch(insertList);
                }
                cacheChatrooms.put(roomId, chatroomCache);
                cache.addCache(WxRobotConstant.CHATROOM_CACHE, cacheChatrooms);
                result = new AsyncResult<>(true);
            }
            return result;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return result;
        }
    }

    /**
     * 保存群成员信息
     *
     * @param list 群成员信息
     * @return
     */
    @Async("saveChatroom")
    public Future<Boolean> saveChatroomMember(List<BotChatroom> list) {
        AsyncResult<Boolean> result = new AsyncResult<>(false);
        try {
            String chatroomId = list.get(0).getChatroomWxid();
            // 获取缓存中的群列表
            Map<String, List<BotChatroom>> chatrooms = cache.getChatrooms();
            List<BotChatroom> existChatroom = chatrooms.get(chatroomId);
            List<BotChatroom> insertList = new ArrayList<>();
            if (PubUtils.isEmpty(existChatroom)) {
                for (BotChatroom botChatroom : list) {
                    botChatroom.setId(PubUtils.getUUID());
                    botChatroom.setPid(robotConfig.getBotWechatId());
                    if (PubUtils.hasSpecialChar(botChatroom.getMemberName())) {
                        // 进行特殊符号过滤
                        StringBuilder sb = new StringBuilder();
                        String[] nameArr = botChatroom.getMemberName().split("");
                        for (String name : nameArr) {
                            if (!PubUtils.matches(name, PubUtils.UTF8CHARACTER)) {
                                sb.append("*");
                            } else {
                                sb.append(name);
                            }
                        }
                        botChatroom.setMemberName(sb.toString());
                    }
                    insertList.add(botChatroom);
                }
            }
            if (PubUtils.isEmpty(insertList)){
                return result;
            }
            // 缓存放回
            chatrooms.put(chatroomId, insertList);
            cache.addCache(WxRobotConstant.CHATROOM_CACHE, chatrooms);
            // 删除后新增
            chatroomService.delByPidAndRoomId(robotConfig.getBotWechatId(), chatroomId);
            chatroomService.saveBatch(insertList);
            result = new AsyncResult<>(true);
        }catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 联系人校验
     *
     * @param contact    联系人
     * @param filterWxId 过滤的wxid
     * @return
     */
    public BotContact checkContact(BotContact contact, String[] filterWxId) {
        if (PubUtils.isEmpty(contact.getWxid()) || "微信支付".equals(contact.getName()) || "微信游戏".equals(contact.getName()) || PubUtils.indexOf(filterWxId, contact.getWxid()) > -1) {
            return null;
        }
        contact.setId(PubUtils.getUUID());
        contact.setPid(robotConfig.getBotWechatId());
        if (PubUtils.hasSpecialChar(contact.getName())) {
            // 进行特殊符号过滤
            StringBuilder sb = new StringBuilder();
            String[] nameArr = contact.getName().split("");
            for (String s : nameArr) {
                if (!PubUtils.matches(s, PubUtils.UTF8CHARACTER)) {
                    sb.append("*");
                }else {
                    sb.append(s);
                }
            }
            contact.setName(sb.toString());
        }
        if (contact.getWxid().endsWith("@chatroom")) {
            // 赋key给群缓存
            contact.setType(2);
        } else if (contact.getWxid().startsWith("gh_")) {
            contact.setType(3);
        } else {
            contact.setType(1);
        }
        return contact;
    }
}
